package com.shuosen.gmall.order.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.shuosen.gmall.bean.OrderDetail;
import com.shuosen.gmall.bean.OrderInfo;
import com.shuosen.gmall.bean.enums.OrderStatus;
import com.shuosen.gmall.bean.enums.ProcessStatus;
import com.shuosen.gmall.config.ActiveMQUtil;
import com.shuosen.gmall.order.mapper.OrderDetailMapper;
import com.shuosen.gmall.order.mapper.OrderInfoMapper;
import com.shuosen.gmall.service.OrderService;
import com.shuosen.gmall.service.PaymentService;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.apache.tomcat.jni.OS;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import tk.mybatis.mapper.entity.Example;

import javax.jms.*;
import javax.jms.Queue;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService  {
    @Autowired
    OrderInfoMapper  orderInfoMapper  ;

    @Autowired
    OrderDetailMapper  orderDetailMapper  ;

    @Autowired
    ActiveMQUtil activeMQUtil;

    @Reference
    PaymentService paymentService ;

    @Override
    public String saveOrder(OrderInfo orderInfo) {
        //设置创建时间
        orderInfo.setCreateTime(new Date());
        //设置失效时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,1);
        orderInfo.setExpireTime(calendar.getTime());
        //生成第三方支付编号
        String  outTradeNo = "ATGUIGU"+System.currentTimeMillis()+""+new Random().nextInt(1000);
        orderInfo.setOutTradeNo(outTradeNo);
        orderInfoMapper.insertSelective(orderInfo);

        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            orderDetail.setOrderId(orderInfo.getId());
            orderDetailMapper.insertSelective(orderDetail);
        }
        //为了跳转到支付页面使用，支付会根据订单id进行支付
        String  orderId = orderInfo.getId();
        return orderId;
    }

    @Override
    public OrderInfo getOrderInfo(String orderId) {
        //通过order
        OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId);
        OrderDetail orderDetail = new OrderDetail() ;
        orderDetail.setOrderId(orderId);
        List<OrderDetail> orderDetailList = orderDetailMapper.select(orderDetail);
        orderInfo.setOrderDetailList(orderDetailList);

        return orderInfo ;

    }

    @Override
    public void updateOrderStatus(String orderId, ProcessStatus paid) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setId(orderId);
        orderInfo.setProcessStatus(paid);
        orderInfo.setOrderStatus(paid.getOrderStatus());
         orderInfoMapper.updateByPrimaryKeySelective(orderInfo);
    }

    @Override
    public void sendOrderStatus(String orderId) {
        Connection connection = activeMQUtil.getConnection();
        String jsonStr = initWareOrder(orderId);
        try {
            connection.start();
            //创建session
            Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
            Queue order_result_queue = session.createQueue("ORDER_RESULT_QUEUE");
            MessageProducer producer = session.createProducer(order_result_queue);
            ActiveMQTextMessage activeMQTextMessage = new ActiveMQTextMessage();
            activeMQTextMessage.setText(jsonStr);
            producer.send(activeMQTextMessage);
            session.commit();
            producer.close();
            session.close();
            connection.close();
        } catch (JMSException e) {
            e.printStackTrace();
        }

    }

    @Override
    public List<OrderInfo> getExpiredOrderList() {
        Example example = new Example(OrderInfo.class);
        example.createCriteria().andEqualTo("orderStatus", OrderStatus.UNPAID).andLessThan("expireTime",new Date());

        List<OrderInfo> orderInfos = orderInfoMapper.selectByExample(example);

        return orderInfos;
    }

    @Override
    @Async
    public void execExpiredOrder(OrderInfo orderInfo) {
        System.out.println(Thread.currentThread().getName());
        //关闭过期订单
        updateOrderStatus(orderInfo.getId(),ProcessStatus.CLOSED);
        //关闭付款信息
        paymentService.closePayment(orderInfo.getId());
    }

    @Override
    public List<OrderInfo> orderSplit(String orderId, String wareSkuMap) {
        List<OrderInfo> subOrderInfoList = new ArrayList<>();
        /***
         * 1：获取原始订单
         * 2:获取wareSkuMap
         * 3:创建新的子订单对象
         * 4：将子订单添加到subOderInfoList 并保存子订单
         * 5：修改原始订单的状态
         */
        OrderInfo orderInfoOrigin = getOrderInfo(orderId);
        List<Map> maps = JSON.parseArray(wareSkuMap, Map.class);
        //判断集合是否为空
        if(maps!=null && maps.size()>0){
            for (Map map : maps) {
                //获取wareId skuIds
                String wareId = (String) map.get("wareId");
               List<String>  skuIds = (List<String>) map.get("skuIds");
                OrderInfo subOrderInfo = new OrderInfo();
                //属性拷贝
                BeanUtils.copyProperties(orderInfoOrigin,subOrderInfo);
                //将OrderInfo设置为null 防止主键重复
                subOrderInfo.setId(null);
                subOrderInfo.setParentOrderId(orderInfoOrigin.getId());
                subOrderInfo.setWareId(wareId);
                //获取OrderDetailList  明细表 根据炒蛋方案中的skuId进行匹配，得到那个的子订单
                List<OrderDetail> orderDetailList = orderInfoOrigin.getOrderDetailList();
                //创建一个新的订单集合
                List<OrderDetail> subOrderDetailList = new ArrayList<>();
                if(orderDetailList!=null && orderDetailList.size()>0){

                    //循环原始订单明细集合
                    for (OrderDetail orderDetail : orderDetailList) {
                        for (String skuId : skuIds) {
                            if(skuId.equals(orderDetail.getSkuId())){
                                orderDetail.setId(null);
                                subOrderDetailList.add(orderDetail);
                            }
                        }
                    }
                    subOrderInfo.setOrderDetailList(subOrderDetailList);
                    subOrderInfo.sumTotalAmount();
                    //7:保存到数据库中
                    saveOrder(subOrderInfo);
                    subOrderInfoList.add(subOrderInfo);
                }
                updateOrderStatus(orderId,ProcessStatus.SPLIT);

            }
        }
        //8：返回一个新生成的子订单列表
        return  subOrderInfoList;
    }

      String initWareOrder(String orderId) {
        //根据orderId 查询OrderInfo 以及OrderDetail 并转换为json字符串
        OrderInfo orderInfo = getOrderInfo(orderId);
         Map map = initWareOrder(orderInfo);
        return JSON.toJSONString(map);
    }

    @Override
    public Map initWareOrder(OrderInfo orderInfo) {
        HashMap map = new HashMap();
        map.put("orderId",orderInfo.getId());
        map.put("consignee", orderInfo.getConsignee());
        map.put("consigneeTel",orderInfo.getConsigneeTel());
        map.put("orderComment",orderInfo.getOrderComment());
        map.put("orderBody",orderInfo.getTradeBody());
        map.put("deliveryAddress",orderInfo.getDeliveryAddress());
        map.put("paymentWay","2");
        map.put("wareId",orderInfo.getWareId());
        List<Map> orderDetailMapList = new ArrayList<>();
        //取出OrderInfo中的OrderDetailList
        List<OrderDetail> orderDetailListOld = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailListOld) {
            //获取skuId
            //获取skuNum
            //获取skuName
            Map orderDetailMap = new HashMap<>();
            orderDetailMap.put("skuId",orderDetail.getSkuId());
            orderDetailMap.put("skuNum",orderDetail.getSkuNum());
            orderDetailMap.put("skuName",orderDetail.getSkuName());
            orderDetailMapList.add(orderDetailMap);
        }
        map.put("details",orderDetailMapList);
        return  map ;
    }
}
